import { Application } from 'egg';
import { DataTypes, Model } from 'sequelize';

export interface ExclusiveOrderItemAttributes {
  id?: number;
  order_id: number;
  dish_id: number;      // 快照：下单时菜品ID
  name: string;         // 快照：菜品名称
  price: number;        // 快照：菜品单价
  pictures: string;
  quantity: number;     // 数量
  created_at?: Date;
  updated_at?: Date;
}

export interface ExclusiveOrderItemInstance extends Model<ExclusiveOrderItemAttributes>, ExclusiveOrderItemAttributes {}

export default (app: Application) => {
  const { INTEGER, STRING, DECIMAL, DATE } = DataTypes;

  const ExclusiveOrderItem = app.model.define<ExclusiveOrderItemInstance>('ExclusiveOrderItem', {
    id: { type: INTEGER, primaryKey: true, autoIncrement: true },
    order_id: { type: INTEGER, allowNull: false, comment: '订单ID' },
    dish_id: { type: INTEGER, allowNull: false, comment: '菜品ID快照' },
    name: { type: STRING(100), allowNull: false, comment: '菜品名称快照' },
    price: { type: DECIMAL(10, 2), allowNull: false, defaultValue: 0, comment: '菜品单价快照' },
    pictures: { type: STRING(500), allowNull: true, comment: '菜品图片' },
    quantity: { type: INTEGER, allowNull: false, defaultValue: 1, comment: '数量' },
    created_at: { type: DATE, allowNull: false, defaultValue: DataTypes.NOW },
    updated_at: { type: DATE, allowNull: false, defaultValue: DataTypes.NOW },
  }, {
    tableName: 'exclusive_order_items',
    comment: '专属餐厅订单项表',
  });

  (ExclusiveOrderItem as any).associate = () => {
    app.model.ExclusiveOrderItem.belongsTo(app.model.ExclusiveOrder, { foreignKey: 'order_id', as: 'order' });
    app.model.ExclusiveOrderItem.belongsTo(app.model.ExclusiveDish, { foreignKey: 'dish_id', as: 'dish' });
  };

  return ExclusiveOrderItem;
};